﻿using System.Text.Json.Serialization;
using Core.Caching;
using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Roles.Caching;
using Core.Identity.Roles.Dtos;
using Core.Models;
using Mapster;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Roles.Features.Queries.GetAll;

public class GetAllRolesQuery : ICacheableRequest<Result<IEnumerable<RoleDto>>>
{
    /// <summary>
    /// 缓存键
    /// </summary>
    [JsonIgnore]
    public string CacheKey => RolesCacheKey.GetAllCacheKey;
    /// <summary>
    /// 缓存选项
    /// </summary>
    [JsonIgnore]
    public IEnumerable<string>? Tags => RolesCacheKey.Tags;
}

public class GetAllRolesQueryHandler :
         IRequestHandler<GetAllRolesQuery, Result<IEnumerable<RoleDto>>>
{
    private readonly IIdentityDbContext _context;

    public GetAllRolesQueryHandler(
        IIdentityDbContext context)
    {
        _context = context;
    }

    public async Task<Result<IEnumerable<RoleDto>>> Handle(GetAllRolesQuery request, CancellationToken cancellationToken)
    {
        return await Result<IEnumerable<RoleDto>>
             .SucceedAsync((await _context.Roles
             .AsNoTracking()
             .OrderByDescending(x => x.Sort)
             .ToListAsync(cancellationToken))
             .Adapt<IEnumerable<RoleDto>>());
    }
}
